package com.example.icongyou;

import com.example.icongyou.bean.Teacher;
import com.example.icongyou.api.TeacherApi;
import com.example.icongyou.retrofit.RetrofitClient;
import com.example.icongyou.utils.SessionManager; // 【新增】导入 SessionManager

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ProfileSettingsFragment extends Fragment {

    private TextView tvAvatarInitial;
    private TextView tvUserName;

    private static final String TAG = "ProfileSettingsFragment";

    // ARG_TEACHER_ID 不再需要，但为保持代码结构先保留
    // public static final String ARG_TEACHER_ID = "teacher_id";

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_profile_settings, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        tvAvatarInitial = view.findViewById(R.id.tv_avatar_initial);
        tvUserName = view.findViewById(R.id.tv_user_name);

        // 【核心修改 1】从 SessionManager 中直接读取当前登录的 Teacher ID
        SessionManager sessionManager = new SessionManager(requireContext());
        String teacherId = sessionManager.getTeacherId();

        if (teacherId != null && !teacherId.isEmpty()) {
            // 检查到 ID，发起网络请求
            fetchAndParseTeacher(teacherId);
        } else {
            // 未获取到 ID，说明用户未登录或会话过期
            Log.e(TAG, "未获取到 Teacher ID，用户未登录或会话过期。");
            if (isAdded()) {
                Toast.makeText(requireContext(), "会话数据缺失，无法加载个人资料。", Toast.LENGTH_LONG).show();
            }
        }
    }

    // 辅助方法 newInstance 仍可保留，但其传递参数的功能在此逻辑下已失效
    public static ProfileSettingsFragment newInstance(String teacherId) {
        // 如果 Fragment 总是从 SessionManager 读取，那么这个参数 teacherId 就被忽略了
        // 但我们保留方法签名，方便 Activity 调用
        return new ProfileSettingsFragment();
    }

    // ------------------- 网络请求和 UI 更新 -------------------

    private void fetchAndParseTeacher(String teacherId) {

        TeacherApi apiService = RetrofitClient.getTeacherApi();
        Call<Teacher> call = apiService.getTeacherById(teacherId);

        call.enqueue(new Callback<Teacher>() {
            @Override
            public void onResponse(Call<Teacher> call, Response<Teacher> response) {
                if (!isAdded()) {
                    return;
                }

                if (response.isSuccessful()) {
                    Teacher teacher = response.body();
                    if (teacher != null) {
                        updateUIWithTeacherData(teacher);
                    } else {
                        Toast.makeText(requireContext(), "获取信息成功，但数据为空。", Toast.LENGTH_LONG).show();
                    }
                } else {
                    Log.e(TAG, "请求失败，状态码: " + response.code());
                    Toast.makeText(requireContext(), "请求失败，请检查服务器状态。", Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onFailure(Call<Teacher> call, Throwable t) {
                if (!isAdded()) {
                    return;
                }
                Log.e(TAG, "网络连接失败", t);
                Toast.makeText(requireContext(), "网络连接失败: " + t.getMessage(), Toast.LENGTH_LONG).show();
            }
        });
    }

    private void updateUIWithTeacherData(Teacher teacher) {
        if (tvAvatarInitial == null || tvUserName == null) {
            return;
        }

        String fullName = teacher.getName();

        String avatarChar = "?";
        if (fullName != null && !fullName.isEmpty()) {
            avatarChar = fullName.substring(0, 1);
        }

        tvAvatarInitial.setText(avatarChar);
        tvUserName.setText(fullName);
    }
}